package com.example.shixun.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.example.shixun.controller.SpendEmail;
import com.example.shixun.pojo.UserDTO;
import com.example.shixun.service.AuthService;
import com.example.shixun.service.EmailService;
import com.example.shixun.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 授权登录接口实现类
 *
 * @author zhuhuix
 * @date 2020-06-15
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AuthServiceImpl implements AuthService {

    // 验证码放入redis缓存过期时间
    @Value("${code.expiration}")
    private Long expiration;

    private final RedisUtils redisUtils;
    private final EmailService emailService;
    private final SpendEmail spendEmail;
    //private final SysUserService sysUserService;

    @Override
    public void sendMailCode(String email) {
        System.out.println("sendMailCode");
        // 查看注册邮箱是否存在
//        if (sysUserService.registerEmailExist(email)) {
//            throw new RuntimeException("注册邮箱已存在");
//        }

//         //获取发送邮箱验证码的HTML模板
//        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("/html/sendEmail.html", TemplateConfig.ResourceMode.CLASSPATH));
//        Template template = engine.getTemplate("email-code.ftl");
//        System.out.println("已获取模板");
        // 从redis缓存中尝试获取验证码
        System.out.println("尝试获取code");
        Object code=new String();
        code = redisUtils.get(email);
        System.out.println("code="+code);
        if (code == null) {
            // 如果在缓存中未获取到验证码，则产生6位随机数，放入缓存中
            code = RandomUtil.randomNumbers(6);
            System.out.println("已生成code"+code);
            if (!redisUtils.set(email, code, expiration)) {
                throw new RuntimeException("后台缓存服务异常");
            }
        }
        System.out.println("code已存入redis");
        // 发送验证码
//        emailService.send(new EmailDto(Collections.singletonList(email),
//                "邮箱验证码", template.render(Dict.create().set("code", code))));
        spendEmail.test1(email,code.toString());
        System.out.println("发送成功：code="+code);
    }
//    @Value("${rsa.private-key}")
//    private String privateKey;
//
//    private final RedisUtils redisUtils;
//    private final EmailService emailService;
//    private final PasswordEncoder passwordEncoder;
//    private final SysUserService sysUserService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean register(UserDTO authUserDTO) {
        // 通过email获取redis中的code
        Object value = redisUtils.get(authUserDTO.getEmail());
        if (value == null || !value.toString().equals(authUserDTO.getCode())) {
            throw new RuntimeException("无效验证码");
        } else {
            redisUtils.del(authUserDTO.getEmail());
        }
        System.out.println("验证码有效！");
        // 如果前端没有传入用户名，则以邮箱号作为用户名进行注册
//        String userName = StringUtils.isEmpty(authUserDto.getUserName()) ? authUserDto.getEmail() : authUserDto.getUserName();
//
//        if (userService.findByUserName(userName) != null) {
//            throw new RuntimeException("用户名已存在");
//        }

        // 创建用户
        /*SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        try {
            sysUser.setPassword(passwordEncoder.encode(RsaUtils.decryptByPrivateKey(privateKey, authUserDto.getPassword())));
        } catch (Exception e) {
            throw new RuntimeException("注册密码异常");
        }
        sysUser.setEmail(authUserDto.getEmail());
        return sysUserService.create(sysUser) != null;*/
        return true;
    }

}
